package com.gxw.rxjavatest.Presenter;

import android.util.Log;

import com.gxw.rxjavatest.activity.View.UserView;
import com.gxw.rxjavatest.model.UserModel;
import com.gxw.rxjavatest.model.bean.User;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by GXW on 2016/4/7 0007.
 * email:603004002@qq.com
 * <p>
 * Presenter作为Model和View通讯的桥梁，需要持有它们的引用。
 */
public class UserPresenter {

    private UserView userView;
    private UserModel userModel;

    public UserPresenter(UserView userView) {
        this.userView = userView;
        userModel = new UserModel();
    }

    public void getUser() {
        userView.showProgressDialog();
        // 这里如果使用 Lambda 会更简洁
        //Lambda表达式的语法
        /**  Lambda基本语法:
         (parameters) -> expression
         或
         (parameters) ->{ statements; }*/
        userModel.getUser().subscribeOn(Schedulers.io())//在非UI线程中执行getUser
                .observeOn(AndroidSchedulers.mainThread())//在UI线程中执行结果
                .subscribe(new Subscriber<User>() {
                    @Override
                    public void onCompleted() {

                        Log.i("sequence","-------------- onCompleted --------------");
                        userView.hideProgressDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("sequence","-------------- onError --------------");
                        userView.hideProgressDialog();
                        userView.showError(e.getMessage());
                    }

                    @Override
                    public void onNext(User user) {
                        Log.i("sequence","-------------- onNext --------------");
                        userView.updateView(user);
                    }
                });

    }

}
